﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using NRadioTray.App.Domain;

namespace NRadioTray.App
{
    public class RadioMenuPlaylistBuilder
    {
        public static ToolStripMenuItem[] GeneratePlaylist()
        {
            List<ToolStripMenuItem> items = new List<ToolStripMenuItem>();

            var playlist = Playlist.LoadPlaylist();

            if (playlist == null || playlist.Radios.Count == 0)
            {
                return null;
            }

            var roots = from root in playlist.Radios
                      where root.Parent.Equals(Guid.Empty)
                      select root;

            foreach (var root in roots)
            {
                var rootItem = new ToolStripMenuItem(root.Name);

                var children = from c in playlist.Radios
                            where c.Parent == root.Id
                            select c;

                if (children.Count() > 0)
                {
                    foreach (var child in children)
                    {
                        var childItem = new ToolStripMenuItem(child.Name);
                        childItem.Tag = child;
                        rootItem.DropDownItems.Add(childItem);
                    }
                }
                else
                {
                    rootItem.Tag = root;
                }

                items.Add(rootItem);
            }

            return items.ToArray();
        }
    }
}
